# coding=utf-8

from werkzeug.utils import secure_filename
from pypinyin import lazy_pinyin
from application import app
import datetime,os,stat,uuid

def uploadByFile(file):
    config_upload = app.config['UPLOAD']
    resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    temp_file_name = ''.join(lazy_pinyin(file.filename))  # 处理中文
    filename = secure_filename(temp_file_name)
    ext = filename.rsplit(".", 1)[1]
    if ext not in config_upload['ext']:
        resp['code'] = -1
        resp['msg'] = "不允许的扩展类型文件"
        return resp

    root_path = app.config["UPLOAD_PREFIX"]
    # 不使用getCurrentDate创建目录，为了保证其他写的可以用，这里改掉，服务器上好像对时间不兼容
    file_dir = datetime.datetime.now().strftime("%Y%m%d")
    save_dir = root_path + file_dir
    if not os.path.exists(save_dir):
        os.mkdir(save_dir)
        os.chmod(save_dir, stat.S_IRWXU | stat.S_IRGRP | stat.S_IRWXO)
    # save_dir = root_path + file_dir + "\\" + package_name
    # if not os.path.exists(save_dir):
    #     os.mkdir(save_dir)
    #     os.chmod(save_dir, stat.S_IRWXU | stat.S_IRGRP | stat.S_IRWXO)

    file_name = str(uuid.uuid4()).replace("-", "") + "." + ext
    file.save("{0}/{1}".format(save_dir, file_name))

    resp['data'] = {
        'file_key': file_dir  + "/" + file_name
    }
    return resp